package com.jhd.fuzhou.view.quantitative;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.SupervisionService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.UploadFile;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.login.SignActivity;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.Upload;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;

public class QuantitativeRecordActivity extends BaseActivity {
    @BindView(R.id.tv_unitName)TextView tv_unitName;//被监督单位
    @BindView(R.id.tv_managementAddress)TextView tv_managementAddress;//地址
    @BindView(R.id.tv_legalRepresentative)TextView tv_legalRepresentative;//负责人
    @BindView(R.id.tv_contactNumber)TextView tv_contactNumber;//联系电话
    @BindView(R.id.tv_creditCode)TextView tv_creditCode;//卫生许可证编号
    @BindView(R.id.tv_totalScore)TextView tv_totalScore;//总得分
    @BindView(R.id.iv_companion)ImageView iv_companion;//监督员签名显示
    @BindView(R.id.iv_supervisor)ImageView iv_supervisor;//陪同人签名显示
    private Bitmap bitmap0;//原始图片
    private Context context=this;
    private Upload upload1,upload2;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_quantitative_record);
    }

    @Override
    protected void processLogic() {
        application.addDocActivity(this);
        onBack();
        bitmap0=((BitmapDrawable)iv_companion.getDrawable()).getBitmap();
        show();

    }
    public void show(){
        tv_unitName.setText(supervisionInspectionVo.getUnitName());
        tv_managementAddress.setText(supervisionInspectionVo.getManagementAddress());//地址
//        tv_contactNumber.setText(supervisionInspectionVo.getContactNumber());//联系电话
        tv_legalRepresentative.setText(supervisionInspectionVo.getLegalRepresentative());//法定代表人
//        tv_creditCode.setText(supervisionInspectionVo.getCreditCode());//卫生许可证编号
        tv_totalScore.setText(getIntent().getStringExtra("totalScore"));//总分
        upload1=supervisionInspectionVo.getUpload1();upload2=supervisionInspectionVo.getUpload2();
        if(upload1!=null){
            Bitmap bitmap=BitmapFactory.decodeFile(getExternalFilesDir(null).getPath()+"/Download/1.png");
            iv_companion.setImageBitmap(bitmap);
        }
        if(upload2!=null){
            Bitmap bitmap=BitmapFactory.decodeFile(getExternalFilesDir(null).getPath()+"/Download/2.png");
            iv_supervisor.setImageBitmap(bitmap);
        }
    }
    @OnClick({R.id.lin_companion,R.id.lin_supervisor,R.id.btn_made_document})//陪同人点击签名,监督员点击签名,制作文书按钮
    public void onClick(View v){
        Intent intent  = new Intent(context, SignActivity.class);
        switch (v.getId()){
            case R.id.lin_companion:
                intent.putExtra("position","1");
                startActivityForResult(intent,1);
                break;
            case R.id.lin_supervisor:
                intent.putExtra("position","2");
                startActivityForResult(intent,1);
                break;
            case R.id.btn_made_document:
                Bitmap bitmap1=((BitmapDrawable)iv_companion.getDrawable()).getBitmap();
                Bitmap bitmap2=((BitmapDrawable)iv_supervisor.getDrawable()).getBitmap();
                if(bitmap1==bitmap0){
                    supervisionInspectionVo.setSign1(false);
                }else{
                    supervisionInspectionVo.setSign1(true);
                }
                if(bitmap2==bitmap0){
                    supervisionInspectionVo.setSign2(false);
                }else{
                    supervisionInspectionVo.setSign2(true);
                }
                Intent intent1=new Intent(context, QuantitativeDocumentActivity.class);
                intent1.putExtra("type","量化分级评分表");
                intent1.putExtra("totalScore",getIntent().getStringExtra("totalScore"));
                intent1.putExtra("shouldScore",getIntent().getStringExtra("shouldScore"));
                startActivity(intent1);
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode ==RESULT_OK) {
            byte[] bis = data.getByteArrayExtra("signBitmap");
            Bitmap bitmap = BitmapFactory.decodeByteArray(bis, 0, bis.length);
            File files=new File(getExternalFilesDir(null).getPath()+"/Download/");
            if(!files.exists())files.mkdirs();
            if(data.getStringExtra("position").equals("1")){
                iv_companion.setImageBitmap(bitmap);
                File file=new File(getExternalFilesDir(null).getPath()+"/Download/1.png");
                if(file.exists())file.delete();
                supervisionInspectionVo.setUpload1(null);
                UploadFile.saveBitmapFile(context,bitmap,"Download/1.png");
            }else if(data.getStringExtra("position").equals("2")){
                iv_supervisor.setImageBitmap(bitmap);
                File file=new File(getExternalFilesDir(null).getPath()+"/Download/2.png");
                if(file.exists())file.delete();
                supervisionInspectionVo.setUpload2(null);
                UploadFile.saveBitmapFile(context,bitmap,"Download/2.png");
            }
        }
    }

    public void uploadSign(int position, String type, String name){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.UC());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, Object> params = new HashMap<>();
        params.put("type", type);
        params.put("isPublic",false);
        File file=new File(getExternalFilesDir(null).getPath()+"/"+ name);
        RequestBody fileRQ=RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part part=MultipartBody.Part.createFormData("file", file.getName(), fileRQ);
        Call<JsonForResult> jsonForResultCall = vs.uploadFileByPos(application.getAccessToken(),params,part);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    if(response.code()==200) {
                        JsonForResult jsonForResult = (JsonForResult)response.body();
                        if (jsonForResult != null && jsonForResult.isSuccess()) {
                            if(position==1){
                                upload1=JSON.parseObject(jsonForResult.getData().toString(), Upload.class);
                            }else if(position==2){
                                upload2=JSON.parseObject(jsonForResult.getData().toString(), Upload.class);
                            }
                        }
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "上传签名失败!";
                //UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
}